package com.nj.dms.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 字符编码过滤器
 *
 * 注解方式配置过滤器 urlPatterns:定义过滤器的映射地址 initParams：定义初始化参数类型为数组
 * WebInitParam：定义指定的一个参数(name ,value)
 */
@WebFilter(urlPatterns = { "/*" }, initParams = { @WebInitParam(name = "enCoding", value = "utf-8") })
public class EncodingFilter implements Filter {

	String enCoding;

	// 获取设置的初始化参数
	public void init(FilterConfig fConfig) throws ServletException {
		enCoding = fConfig.getInitParameter("enCoding");
		// System.out.println("enCoding=" + enCoding + " - " + this.getClass());
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		// 设置请求和响应的字符编码
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		request.setCharacterEncoding(enCoding);
		response.setCharacterEncoding(enCoding);

		// System.out.println("编码过滤器执行一次" + this.getClass());

		// 将request对象和response对象传递下去
		chain.doFilter(req, res);

	}

	@Override
	public void destroy() {

	}

}
